package com.wang.sse.service.impl;

import com.wang.sse.service.SseEmitterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: wangning1@abupdate.com
 * @date: 2023-12-14 13:37
 **/
@Slf4j
@Service
public class SseEmitterServiceImpl implements SseEmitterService {

    /**
     * messageId的 SseEmitter对象映射集
     */
    private final ConcurrentHashMap<String, SseEmitter> sseEmitterMap = new ConcurrentHashMap();

    /**
     * 创建连接
     *
     * @param id
     * @return
     */
    @Override
    public SseEmitter connect(String id) {
        SseEmitter sseEmitter = sseEmitterMap.get(id);
        if (Objects.isNull(sseEmitter)){
            sseEmitter = new SseEmitter();
            sseEmitter.onCompletion(() -> {
                sseEmitterMap.remove(id);
                log.info("连接断开：{}", id);
            });
            sseEmitter.onTimeout(() -> {
                sseEmitterMap.remove(id);
                log.info("连接超时：{}", id);
            });
            sseEmitter.onError((throwable) -> {
                sseEmitterMap.remove(id);
                log.info("连接错误：{}", id);
            });
            sseEmitterMap.put(id, sseEmitter);
            log.info("连接成功：{}", sseEmitter);
            return sseEmitter;
        }
        log.info("连接成功：{}", sseEmitter);
        return sseEmitter;

    }

    /**
     * 单发
     *
     * @param id
     * @param message
     */
    @Override
    public void publisher(String id, String message) {
        SseEmitter sseEmitter = sseEmitterMap.get(id);
        if (Objects.isNull(sseEmitter)){
            return;
        }
        try {
            sseEmitter.send(message);
            log.info("发送消息：{}", sseEmitter);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 消息发送
     *
     * @param message
     */
    @Override
    public void sendMessage(String message) {

        // sseEmitterMap.forEach((id, sseEmitter) -> {
        //     try {
        //         sseEmitter.send(message);
        //     } catch (IOException e) {
        //         e.printStackTrace();
        //     }
        // });
    }

}